/**
 * Created by lwy on 2017/6/22.
 */


//关键字搜索
function kewSearch(){
    $.ajax({
        url:'/openSearchC/nearbySuggest.json',
        dataType:'json',
        data:{
            keywords:$('#keyword').val(),
        },
        type:'post',
        success:function(data){
            if(data.code==1){
                $('.connect-box').empty();
                for(var i=0;i<data.result.length;i++){
                    $('<p><img src="../img/search-icon.png" alt="搜索结果"><span>'+data.result[i]+'</span></p>').appendTo($('.connect-box'));
                }
            }
            $('.connect-box p').click(function(){
                var keywords = $(this).find('span').html();
                var kwdCacheKey = 'h_kwd_list';
                //存储搜索记录
                searchAll(keywords);
            })
        }
    })
}
//输入
$(function(){
    if($('#keyword').val()==""||$('#keyword').val()=='输入您想要的内容'){
        $('.sousuo').hide();
        $('.connect-box').empty();
    }else{
        $('.sousuo').show();
        $('#keyword').css('background','#e8e8e8');
    }
})
document.getElementById('keyword').oninput=function(){
    if($(this).val()==""||$(this).val()=='输入您想要的内容'){
        $('.sousuo').hide();
        $('.connect-box').empty();
    }else{
        $('.sousuo').show();
        $('#keyword').css('background','#e8e8e8');
    }
    kewSearch();
}

//清除按钮清除输入框内容
$('.sousuo').click(function(){
    $('#keyword').val('');
    $('.connect-box').empty();
})

//热门搜索
$(function(){
    $.ajax({
        url:'/openSearchC/popSearch.json',
        dataType:'json',
        data:{
            city:getItem('locationCity'),
        },
        type:'post',
        success:function(data){
            if(data.code==1){
                var data = data.datas;
                //var hotSearchHtml = '';
                for(var i=0;i<data.length;i++){
                    $('<div class="searchDiv">'+data[i]+'</div>').appendTo($('.hotsearch-box'));
                }
                //hotSearchHtml+='</div>';
                //$(hotSearchHtml).appendTo($('.hotsearch-box'))
                //var hotSearchHtml2='';
                //hotSearchHtml2+='<div class="hot-search-line">';
                //for(var k=3;k<6;k++){
                //    hotSearchHtml2+='<span class="hot-span">'+data[k]+'</span>';
                //}
                //hotSearchHtml2+='</div>';
                //$(hotSearchHtml2).appendTo($('.hotsearch-box'));
                //var hotSearchHtml3='';
                //hotSearchHtml3+='<div class="hot-search-line">';
                //for(var a=6;a<9;a++){
                //    hotSearchHtml3+='<span class="hot-span">'+data[a]+'</span>';
                //}
                //hotSearchHtml3+='</div>';
                //$(hotSearchHtml3).appendTo($('.hotsearch-box'))
            }
        }
    })
})

//热搜点击
mui('body').on('tap','.searchDiv',function(){
    var keywords = $(this).html();
    $('#keyword').val(keywords);
    //存储搜索记录
    searchAll(keywords);
})

//历史记录点击
mui('body').on('tap','.history',function(){
    var keywords = $(this).find('span').html();
    $('#keyword').val(keywords);
    //存储搜索记录
    searchAll(keywords);
})

//软键盘搜索
$("#keyword").on('keypress',function(e) {
    var keycode = e.keyCode;
    var searchName = $(this).val();
    var kwdCacheKey = 'h_kwd_list';     //定义数据存储对象名
    if(keycode=='13') {
        //存储搜索记录
        searchAll(searchName);
    }
});

$('#search-right').click(function(){
    var searchName = $('#keyword').val();
    searchAll(searchName);
})

//搜索合并方法
function searchAll(name){
    if($('#keyword').val()==''||$('#keyword').val()=='输入您想要的内容'){
        mui.toast('请输入搜索内容');
        return;
    }
    var kwdCacheKey = 'h_kwd_list';
    var currentKwdKey = 'k_'+name,       //当前搜索值对应的键值
        currentKwdList = {},                    //创建json对象
        kwdStr = getItem(kwdCacheKey);     //获取历史搜索内容（字符串）
    if(kwdStr !== null){
        var kwdList = JSON.parse(kwdStr);       //将历史搜索内容转化为对象
    }

    currentKwdList[currentKwdKey] = name; //将当前输入关键字动态加入新创建json对象中

    if(kwdList == undefined){   //如果不存在历史搜索内容，直接将当前搜索内容转化为字符串
        var kwdTxt = JSON.stringify(currentKwdList);
    }else{
        //合并对象（当前搜索内 和 历史 搜索内容）
        var kwdTxtObj = mergeToRepeat(currentKwdList,kwdList);
        //转化为序列化json字符串格式
        kwdTxt = JSON.stringify(kwdTxtObj);
    }
    setItem(kwdCacheKey, kwdTxt);  //存入localStorage
    var kwdLength = getJsonLength(kwdList);

    if(kwdLength>30){
        removeItem('h_kwd_list');
        //var splitData = JSON.stringify(kwdList).split(',');
        //var group = '';
        //splitData.splice(1,splitData.length-5);
        //splitData.join(',');
        //console.log(splitData);
        //for(var i=0;i<splitData.length;i++){
        //group+=splitData[i]+','
        //}
        //group=group.substring(0,group.Length-1);
        //console.log(JSON.parse(group));
        //console.log(group);
        //console.log(kwdList);
        //kwdList = group;
        //console.log(JSON.stringify(kwdList));
    }
    window.location.href=encodeURI(encodeURI("shop_list.html?keywords="+name+"&page=1"));
}

//获取存储json长度
function getJsonLength(jsonData){

    var jsonLength = 0;

    for(var item in jsonData){

        jsonLength++;

    }

    return jsonLength;

}

$(function(){
    upData();
    clearkey();
})


function upData(){  //取数据
    var kwdTxt = getItem('h_kwd_list') ? getItem('h_kwd_list') : undefined;
    //var kwdTxt = window.localStorage.h_kwd_list ? window.localStorage.h_kwd_list : undefined;
    if(kwdTxt !== undefined){
        kwdTxtObj = JSON.parse(kwdTxt);
        //console.log(kwdTxtObj);

        for(var attr in kwdTxtObj){ //遍历对象
            var item = '<div class="history"><img src="../img/history-search.png" alt=""><span>'+kwdTxtObj[attr]+'</span></div>';
            $('.historyBox').append(item);
        }
    }else{
        $('.history_box').hide();
    }
}

//清空历史记录
function clearkey(){
    $('.clear-history').on('tap', function(){
        //localStorage.clear();   //删除所有localStorage的值
        removeItem('h_kwd_list'); //删除h_kwd_list这个键值的里面所有的值
        $('.history_box').hide();
    })
}

//遍历两个对象合成一个并将两个对象中重复的键值的值去掉前一个
function mergeToRepeat(json1,json2){
    var resJson={};
    for(var i in json1){
        resJson[i]=json1[i];
    }
    for (var i in json2) {
        resJson[i]=json2[i];
    };
    return resJson;
}